$(function () {

	app.init();
});

var app = {
	adminPath: "admin_express",
	init() {
		this.toggleAside();
		this.deleteConfirm();
		this.resizeIframe();
		this.submitConfirm();
		this.changeStatus();
		this.changeSort()
	},
	deleteConfirm() {
		$('.delete').click(function () {
			const flag = confirm('您确定要删除吗?');
			return flag;
		});
	},
	submitConfirm() {
		$('button.btn').click(function () {
			const flag = confirm('您确定要提交吗?');
			return flag;
		});
	},
	resizeIframe() {
		const heights = document.documentElement.clientHeight - 100;
		let rightMainObj = document.getElementById('rightMain')

		if (rightMainObj) {
			rightMainObj.height = heights;
		}
	},
	toggleAside() {
		$('.aside h4').click(function () {
			$(this).siblings('ul').slideToggle();
		})
	},
	changeStatus() { 
		let adminPath = this.adminPath
		$('.chStatus').click(function () {

			let el = $(this)
			let id = el.attr('data-id')
			let model = el.attr('data-model')
			let field = el.attr('data-field')
			let status = el.attr('status')

			$.get('/'+adminPath+'/chStatus', {
				id,
				model,
				field,
				status
			}, function (response) { 
				console.log(response.message);
				if (response.success) {
					if (el.attr('src').indexOf('yes') !== -1) {
						el.attr('src', '/admin/images/no.gif')
					} else {
						el.attr('src', '/admin/images/yes.gif')
					}
				} else {
					console.log(response);
				}
			})
		})
	},
	changeSort() {
		let adminPath = this.adminPath
		$('.chSort').click(function () {
			let el = $(this)
			let id = el.attr('data-id')
			let model = el.attr('data-model')
			let field = el.attr('data-field')

			let sortNum = el.html()
			let inputEl = $(`<input type="number" min="1" max="1000" style="width: 80px;"/>`)

			inputEl.click(function (e) {
				e.stopPropagation()
			})
			
			el.html(inputEl)

			inputEl.trigger('focus').val(sortNum)

			inputEl.blur(function () {
				let inputSort = this.value <= 0 ? 1 : this.value > 1000 ? 1000 : this.value

				$.get('/'+adminPath+'/chSort', {
					id,
					model,
					field,
					inputSort
				}, function (response) { 
					if (response.success) {
						el.html(inputSort)
					} else {
						console.log(response);
					}
				})
			})
		})
	}
};

$(window).resize(function () {
	app.resizeIframe()
})